// pages/alarmDetail/alarmDetail.js
const httprequest = require('../../utils/http_utils.js')
const dateTimePicker = require('../../utils/dateTimePicker.js')
const common = require('../../utils/common.js')
const dateutil = require('../../utils/date_util.js')
var app = getApp();
// var fileArr = new Array();
var header = {
  'content-type': "application/json",
  "Cookie": "",
}
var session_id = wx.getStorageSync('SessionId'); //本地取存储的sessionID
if (session_id != "" && session_id != null) {
  header.Cookie = 'JSESSIONID' + session_id
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailstitle: "报警详情",
    heightInfo: 'auto',
    opendia1: false,
    opendia2: false,
    input: false,
    button: true,
    panel: false,
    spaeach: 1,
    spaeachicon: 'icon ion-ios-keypad',
    detclasses: 'wrapper details',
    detailData: {},
    isClickShow: true,
    loading2: false,
    contentData: [], //报警消息附件内容
    // isAdministrators:true
    isHidden: true, //是否隐藏dialog
    titleMsg: " ", //消息标题
    cancleBtn: false,
    isTrue: 0, // 0显示确认完成按钮  1显示确任误报按钮 2显示 确认生成工单按钮
    FileGuid: [],
    imgs: [], //选择图片地址
    images:[], //下载图片地址
  },

  //拍照上传图片
  chooseimage: function() {
    var that = this
    var fileArr = that.data.contentData
    var fileRowGuid = that.data.FileGuid;
    var newImgs = that.data.imgs;
    var newName = new Date().getTime();
    var sFile = new Array();
    wx.chooseImage({
      count: that.data.imgs.length,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths.length + '------------------------------拍照长度')
        var newName = new Date().getTime();
        for (var i = 0; i < tempFilePaths.length; i++) {
          newImgs.push(tempFilePaths[i])
          //压缩图片
          wx.compressImage({
            src: tempFilePaths[i],
            quality: 80,
            success: function(res) {
              // console.log(res)
              var tempimgpath = res.tempFilePath;
              //获取base64
              wx.getFileSystemManager().readFile({
                filePath: tempimgpath,
                encoding: 'base64',
                success: function(res) {
                  // console.log('base64---' + JSON.stringify(res.data))
                  var newGuid = common.initGuid()
                  var base = JSON.stringify(res.data);
                  var paramLocal = {
                    fileUrl: "data:image/jpeg;base64," + res.data,
                    fileName: newName + '.jpg',
                    alermId: that.data.detailData.id
                  };

                  fileArr.push(paramLocal)
                  var param = {
                    fileUrl: res.data, //图片全地址
                    fileName: newName + '.jpg'
                  };
                  sFile.push(param)

                  // var proGuid = wx.getStorageSync("UserInfo").AppLogin.ProjectGuid

                  var paramInfo = {
                    alermId: that.data.detailData.id,
                    fileData: sFile,
                    ProjectGuid: app.globalData.ProjectGuid
                  };

                  console.log(JSON.stringify(paramInfo))

                  wx.showLoading({
                    title: "正在处理中...",
                  })

                  wx.request({
                    url: app.globalData.apiInfo.UploadFileApi,
                    data: JSON.stringify(paramInfo),
                    method: "POST",
                    header: header,
                    success: function(data) {
                      // console.log("*********" + JSON.stringify(data))
                      if (data != null) {
                        var res = data.data;
                        var resInfo = JSON.parse(res)
                        // console.log(JSON.stringify(resInfo))
                        if (resInfo != null) {
                          if (resInfo.Header.Status == true) {
                            that.setData({
                              contentData: fileArr
                            })
                            // if (wx.getStorageSync('fileInfo') == null) {
                            //   wx.setStorageSync("fileInfo", JSON.stringify(fileArr))
                            // }
                            wx.showToast({
                              title: '附件上传成功！',
                              icon: 'success',
                              duration: 2000
                            })
                          } else {
                            wx.showToast({
                              title: '附件上传失败！！',
                              icon: 'none',
                              duration: 2000
                            })
                          }
                        } else {
                          wx.showToast({
                            title: '附件上传失败！！',
                            icon: 'none',
                            duration: 2000
                          })
                        }
                      } else {
                        console.log('-----------------上传失败')
                      }
                      wx.hideLoading();
                    },
                    fail: function(error) {
                      wx.showToast({
                        title: '附件上传失败！！',
                        icon: 'none',
                        duration: 2000
                      })
                      wx.hideLoading();
                    }
                  })
                },
                fail: function(err) {
                  console.error(('获取base64失败', err))
                }
              })
            },
            fail: function(err) {
              console.error(('压缩图片失败', err))
            }
          })
        }
        that.setData({
          imgs: newImgs,
          picnum: that.data.imgs.length,
          FileGuid: fileRowGuid
        })
        if (that.data.picnum >= 5) {
          that.setData({
            paddingbottom_height: 400
          })
        } else {
          that.setData({
            paddingbottom_height: 250
          })
        }
        console.log('FileGuid', that.data.FileGuid)
      }
    })
  },

  //完成操作
  wancheng: function() {
    var _this = this;
    var param = {
      message_type: '1000302',
      to_appid: '40564',
      content: {
        id: _this.data.detailData.id,
        time: _this.data.detailData.time,
        status: 'processed',
        processor: {
          id: null,
          name: null
        },
        process_description: '',
        process_extend: {}
      },
      ProjectGuid: app.globalData.ProjectGuid
    };
    try {
      wx.showLoading({
        title: "正在处理中...",
      })
      wx.request({
        url: app.globalData.apiInfo.changeStatusDataApi,
        data: JSON.stringify(param),
        method: "POST",
        header: header,
        success: function(data) {
          var res = null;
          try {
            res = JSON.parse(data.data);
            wx.hideLoading();
            if (res.code == "0") {
              _this.setData({
                detailData: param
              })
              wx.showToast({
                title: '处理成功！',
                icon: 'success',
                duration: 2000
              })
              _this.setData({
                isHidden: true
              })
              wx.navigateBack({
                delta: 1
              })

            }
          } catch (e) {
            _this.setData({
              isHidden: true
            })

            wx.redirectTo({
              url: '/pages/alarm/alarm'
            })
          }
        },
        fail: function(error) {
          wx.hideLoading();
          wx.showToast({
            title: '处理失败！',
            icon: 'none',
            duration: 2000
          })
          _this.setData({
            isHidden: true
          })
        }
      })
    } catch (e) {
      wx.hideLoading();
      wx.showToast({
        title: '处理失败！',
        icon: 'none',
        duration: 2000
      })
      _this.setData({
        isHidden: true
      })
      console.log(e.message);
    }
  },

  //误报操作
  wubao: function() {
    var _this = this;
    var param = {
      ProjectGuid: app.globalData.ProjectGuid,
      message_type: '1000302',
      to_appid: '40564',
      content: {
        id: _this.data.detailData.id,
        time: _this.data.detailData.time,
        status: 'misreport',
        processor: [],
        process_description: '',
        process_extend: {}
      }
    };
    try {
      wx.showLoading({
        title: "正在处理中...",
      })
      wx.request({
        url: app.globalData.apiInfo.changeStatusDataApi,
        data: JSON.stringify(param),
        method: "POST",
        header: header,
        success: function(data) {
          var res = null;
          try {
            res = JSON.parse(data.data);
            wx.hideLoading();
            if (res.code == "0") {
              _this.setData({
                detailData: param
              })
              wx.showToast({
                title: '处理成功！',
                icon: 'success',
                duration: 2000
              })
              _this.setData({
                isHidden: true
              })

              wx.navigateBack({
                delta: 1
              })

            }
          } catch (e) {
            _this.setData({
              isHidden: true
            })

            wx.redirectTo({
              url: '/pages/alarm/alarm'
            })
          }
        },
        fail: function(error) {
          wx.hideLoading();
          wx.showToast({
            title: '处理失败！',
            icon: 'none',
            duration: 2000
          })
          _this.setData({
            isHidden: true
          })
        }
      })
    } catch (e) {
      wx.hideLoading();
      wx.showToast({
        title: '处理失败！',
        icon: 'none',
        duration: 2000
      })
      _this.setData({
        isHidden: true
      })
      console.log(e.message);
    }
  },

  //生成工单操作
  buildworder: function() {
    console.log("正在处理生成工单");
    var that = this;
    var MessageInfo = that.data.optionwid.type + ((that.data.optionwid.subType) ? "-" + that.data.optionwid.subType : "")
    console.log(wx.getStorageSync('UserInfo'))
    var param = {
      UserRowGuid: wx.getStorageSync('UserInfo').AppLogin.RowGuid,
      DeviceCode: that.data.optionwid.position.wId,
      MessageInfo: MessageInfo,
      ErrorLevel: that.data.detailData.level,
      Description: that.data.detailData.description,
      fileGuid: that.data.optionwid.file_id,
      TypeInfo: 8,
    };
    wx.showLoading({
      title: "正在处理中...",
    })
    wx.request({
      url: httprequest.host + "api/Mobile/CreateWorkOrdersByAlarm",
      data: JSON.stringify(param),
      method: "POST",
      header: header,
      success: function(data) {
        console.log(data)

        var res = JSON.parse(data.data)
        console.log(res)
        wx.hideLoading();
        that.setData({
          isHidden: true
        })

        if (res.flag) {
          wx.showToast({
            title: "生成工单成功",
            icon: 'success',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: res.ErrorMsg,
            icon: 'none',
            duration: 2000
          })
        }

      },
      fail: function(error) {
        wx.hideLoading();
        wx.showToast({
          title: '处理失败！',
          icon: 'none',
          duration: 2000
        })
        that.setData({
          isHidden: true
        })
      }
    })
  },

  //处理完成dialog
  showcomplete: function() {
    var that = this;
    that.setData({
      isHidden: false,
      titleMsg: "确定已完成该任务？",
      isTrue: 0,
    })
  },

  //确认误报dialog
  showerror: function() {
    var that = this;
    that.setData({
      isHidden: false,
      titleMsg: "确定该单为误报？",
      isTrue: 1
    })
  },

  //预览图片
  preview: function(e){
    var img = e.currentTarget.dataset.img
    var index = e.currentTarget.dataset.index
    wx.previewImage({
      current: img[index],
      urls: img
    })
  },

  // showworder
  showworder: function() {
    var that = this;
    that.setData({
      isHidden: false,
      titleMsg: "确认生成工单吗？",
      isTrue: 2
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    console.log(JSON.stringify(options));
    console.log(JSON.stringify(wx.getStorageSync('fileInfo')) + "---------------------报警")

    this.setData({
      optionwid: JSON.parse(options.msg)
    })

    var _this = this;
    var res = JSON.parse(options.msg);
    if (res != null) {
      var data = res;
      console.log(JSON.stringify(data));
      var processor = '';
      var image = null;
      if (data.processor != null) {
        processor = data.processor.name;
      }
      if (data.image == undefined) {
        image = {};
      } else {
        image = data.image;
      }
      var param = {
        level: data.level,
        type: data.type,
        time: data.time,
        sub_type: data.sub_type,
        description: data.description,
        location: data.positionText,
        id: data.id,
        processor: processor,
        dinCode: data.position == undefined ? data.din : data.position.din,
        image: image,
        imageData: data.imageData
      };
      console.log(param.id);

      //获取位置信息
      try {
        wx.showLoading({
          title: "正在加载中...",
        })
        wx.request({
          url: app.globalData.apiInfo.locationDataApi,
          data: {
            dinCode: param.dinCode
          },
          method: "POST",
          header: header,
          success: function(data) {
            wx.hideLoading();
            if (data.length > 0) {
              var res = JSON.parse(data);
              if (res.success == true) {
                if (res.data != null && res.data != undefined) {
                  param.location = res.data.positionText;
                } else {
                  param.location = '-';
                }
              }
            }
            _this.setData({
              detailData: param
            })
            console.log(JSON.stringify(_this.data.detailData))
          },
          fail: function(error) {
            wx.hideLoading();
          }
        })
      } catch (e) {
        wx.hideLoading();
        _this.setData({
          detailData: param
        })
        console.log(e.message);
      }

      //获取报警画面
      try {
        if (data.image == null) {
          param.imageData = '../images/zanwu.png';
          $('.imageDataInfo').css('width', '120px');
        } else {
          wx.showLoading({
            title: "正在加载中...",
          })
          if (data.image.type == 1) {
            param.imageData = data.image.data
            _this.setData({
              detailData: param
            })
          } else {
            wx.request({
              url: app.globalData.apiInfo.downLoadApi,
              data: {
                ProjectGuid: app.globalData.ProjectGuid,
                file_id: data.image.data
              },
              method: "POST",
              header: header,
              success: function(data) {
                wx.hideLoading();
                var imageList = _this.data.images;
                var res = JSON.parse(data.data);
                if (res.code == 0) {
                  imageList.push(res.data.downloadUrl)
                }
                _this.setData({
                  images: imageList
                })
              },
              fail: function(error) {
                wx.hideLoading();
              }
            })
          }

        }
      } catch (e) {
        console.log(JSON.stringify(e));
      }

      if (data.status == 'processed') {
        //_this.isClickShow = false;
      } else {
        //_this.isClickShow = true;
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})